package de.tudarmstadt.gdi1.project;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;

import de.tudarmstadt.gdi1.project.alphabet.Alphabet;
import de.tudarmstadt.gdi1.project.exception.InvalidAlphabetException;

/**
 * a alphabet of the used characters in your kryptologie
 * @author Julian
 *
 */

public class Charset implements Alphabet {
	
	/**
	 * creates the alphabet with the given characters
	 * @param characters a collection of characters
	 * @throws InvalidAlphabetException
	 */

	public Charset(Collection<Character> characters) throws InvalidAlphabetException {
		charset = new LinkedList<Character>(); 			//initialize the list charset
		for(Character element : characters){ 			//adds every character from the collection into the list if its not already contained
			if(!charset.contains(element))
				charset.add(element);
		}
		if (characters.size() != charset.size())		// proofs if the collection and list are the same size, if not there must have been a character twice
			throw new InvalidAlphabetException();		
	}

	private LinkedList<Character> charset; // the list of characters

	@Override
	public int getIndex(char chr) {
		return charset.indexOf(chr);
	}

	@Override
	public char getChar(int index) {
		int i = index;
		if(i >= charset.size()){		// loops the list if index is higher than the size of the list 
			i = i % charset.size();
		}
		return charset.get(i);
	}

	@Override
	public int size() {
		return charset.size();
	}

	@Override
	public boolean contains(char chr) {
		return charset.contains(chr);
	}

	@Override
	public boolean allows(String word) {
		boolean b = true;
		for (int i = 0; i < word.length(); i++) {			//proofs if every letter in the String is contained inside the alphabet
			b = (b && charset.contains(word.charAt(i)));
		}
		return b;
	}

	@Override
	public String normalize(String input) {
		StringBuilder b = new StringBuilder();
		for (int i = 0; i < input.length(); i++) {
			if (charset.contains(input.charAt(i))) {
				b.append(input.charAt(i));
				b.trimToSize();
			}
		}
		return b.toString();
	}

	@Override
	public char[] asCharArray() {
		char[] c = new char[charset.size()];
		int i = 0;
		for(char a : charset){
			c[i++] = a;
		}
		return c;
	}

	@Override
	public Iterator<Character> iterator() {
		Iterator<Character> iterator = charset.iterator();
		return iterator;
	}
	

}
